package com.example.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.AutoLog;
import com.example.common.Result;
import com.example.domain.entity.Params;
import com.example.domain.entity.Room;
import com.example.service.RoomService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@RequestMapping("/room")
public class RoomController {

    private static final Logger log = LoggerFactory.getLogger(RoomController.class);

    @Autowired
    private RoomService roomService;
    
    @GetMapping("/findAll")
    public Result findAll() {
        List<Room> list = roomService.findAll();
        return Result.success(list);
    }

    @PostMapping
    @AutoLog("增加或修改自习室信息")
    public Result save(@RequestBody Room room) {
        if (room.getId() == null) {
            roomService.add(room);
        } else {
            roomService.update(room);
        }
        return Result.success();
    }

    @GetMapping("/search")
    public Result findBySearch(Params params) {
        log.info("拦截器已放行，正式调用接口内部，查询自习室信息");
        Page<Room> info = roomService.findBySearch(params);
        return Result.success(info);
    }

    @DeleteMapping("/{id}")
    @AutoLog("删除了一个自习室信息")
    public Result delete(@PathVariable Integer id) {
        roomService.delete(id);
        return Result.success();
    }
    
    @GetMapping("/echarts/bie")
    public Result bie() {
        // 查询出所有自习室
        List<Room> list = roomService.findAll();
        Map<String, Long> collect = list.stream()
                .filter(x -> ObjectUtil.isNotEmpty(x.getTypeName()))
                .collect(Collectors.groupingBy(Room::getTypeName, Collectors.counting()));
        // 最后返回给前端的数据结构
        List<Map<String, Object>> mapList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(collect)) {
            for (String key : collect.keySet()) {
                Map<String, Object> map = new HashMap<>();
                map.put("name", key);
                map.put("value", collect.get(key));
                mapList.add(map);
            }
        }
        return Result.success(mapList);
    }
}
